package com.winexpress.util;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;

public class Log {

    public Log() {
    }
    
    public static void info(String input) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            writeLog("INFO: " + sdf.format(cal.getTime()) + " " + input+"\n\n\r");
        } catch (IOException ex) {
            Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static void error(String input){
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            writeLog("ERROR: " + sdf.format(cal.getTime()) + " " + input+"\n\n\r");
        } catch (IOException ex) {
            Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void writeLog(String input) throws IOException {

        AmazonS3 s3 = new AmazonS3Client((new PropertiesCredentials(Log.class.getResourceAsStream("AwsCredential.properties"))));
        String bucketName = "winexpress-grp6";
        String objKey = "log.txt";

        S3Object object = s3.getObject(new GetObjectRequest(bucketName, objKey));
        InputStream oldLog = object.getObjectContent();
        String logContent = IOUtils.toString(oldLog);
        logContent=logContent.concat("\n\n"+input);
        InputStream inputStream = new ByteArrayInputStream(logContent.getBytes());
        
        InputStream is = new ByteArrayInputStream(logContent.getBytes());
        byte[] contentBytes = IOUtils.toByteArray(is);
        Long contentLength = Long.valueOf(contentBytes.length);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(contentLength);

        PutObjectRequest putObject = new PutObjectRequest(bucketName, objKey, inputStream, metadata);
        s3.putObject(putObject);
    }
}
